import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pojo/vo/UserVo.dart';

class Greetings extends StatefulWidget {
  const Greetings(
      {
        super.key,
        this.greeting = "美好的一天从这里开始",
        this.userNameSize = 37.0,
        this.greetingSize = 14.0
      });

  final String greeting;
  final double userNameSize;
  final double greetingSize;

  @override
  State<Greetings> createState() => _GreetingsState();
}

class _GreetingsState extends State<Greetings> {
  String name = "";

  @override
  void initState() {
    super.initState();
    // 组件初始化时尝试解析用户信息
    _updateUserName();
  }

  Future<void> _updateUserName() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString("currentUser");
    if (userJson != null) {
      UserVo user = UserVo.fromJson(json.decode(userJson));
      setState(() {
        name = user.name!;
      });
    }
  }

  String _getGreetingByTime() {
    var hour = DateTime.now().hour;
    if (hour >= 5 && hour < 9) {
      return "早安，一起迎接新的一天";
    } else if (hour >= 9 && hour < 12) {
      return "上午好，来背背单词吧";
    } else if (hour >= 12 && hour < 18) {
      return "下午好，继续加油";
    } else if (hour >= 18 && hour < 22) {
      return "今天将结束，每天继续努力";
    } else {
      return "夜深了，记得休息";
    }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 95,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "Hi ",
                style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: widget.userNameSize - 10,
                    color: Theme.of(context).colorScheme.primary),
              ),
              Text(
                name,
                style:
                TextStyle(fontWeight: FontWeight.w500, fontSize: widget.userNameSize),
              ),
            ],
          ),
          Text(
            _getGreetingByTime(),
            style: const TextStyle(
                fontWeight: FontWeight.w300,
                // fontStyle: FontStyle.italic,
                fontSize: 19
            ),
          ),
        ],
      ),
    );
  }
}